<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <!-- 选手选择 -->
      <el-form-item label="选手" prop="playerId">
        <el-select
          v-model="form.playerId"
          placeholder="请选择选手"
          style="width: 100%"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 类型选择 -->
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择类型"
          style="width: 100%"
        >
          <el-option label="图文" value="image"></el-option>
          <el-option label="视频" value="video"></el-option>
        </el-select>
      </el-form-item>

      <!-- 文案输入 -->
      <el-form-item label="文案">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="请输入文案内容"
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 媒体上传 -->
      <el-form-item label="媒体内容" prop="mediaFiles">
        <el-upload
          :action="'#'"
          :http-request="handleUpload"
          list-type="picture-card"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :limit="9"
          accept="image/*,video/*"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            支持图片或视频格式，图片最多9张
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listPlayer } from "@/api/player";
import { put, getFileNameUUID, getFileName } from "@/utils/ali-oss";

export default {
  name: "EditSquare",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      title: "新增动态",
      form: {
        playerId: undefined,
        type: undefined,
        content: "",
        mediaFiles: [],
      },
      rules: {
        playerId: [
          { required: true, message: "请选择选手", trigger: "change" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        mediaFiles: [
          { required: true, message: "请上传媒体内容", trigger: "change" },
        ],
      },
      playerOptions: [],
      fileList: [],
    };
  },
  created() {
    this.getPlayerOptions();
  },
  methods: {
    getPlayerOptions() {
      listPlayer().then((response) => {
        this.playerOptions = response.rows.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      });
    },
    handleUpload(params) {
      const file = params.file;
      return new Promise((resolve, reject) => {
        const fileName = getFileNameUUID() + getFileName(file.name);
        put(fileName, file)
          .then((result) => {
            if (result) {
              this.form.mediaFiles.push(fileName);
              resolve();
            } else {
              reject(new Error("上传失败"));
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    beforeUpload(file) {
      // 判断文件类型
      const isImage = file.type.startsWith("image/");
      const isVideo = file.type.startsWith("video/");

      if (!isImage && !isVideo) {
        this.$message.error("只能上传图片或视频文件!");
        return false;
      }

      // 如果已经上传了视频，不能再上传其他文件
      if (this.fileList.some((f) => f.raw && f.raw.type.startsWith("video/"))) {
        this.$message.error("视频只能上传一个文件!");
        return false;
      }

      // 如果当前是视频，且已有其他文件，不能上传
      if (isVideo && this.fileList.length > 0) {
        this.$message.error("视频不能与其他文件一起上传!");
        return false;
      }

      // 图片数量限制
      if (isImage && this.fileList.length >= 9) {
        this.$message.error("最多只能上传9张图片!");
        return false;
      }

      return true;
    },
    handleRemove(file) {
      const index = this.form.mediaFiles.indexOf(file.name);
      if (index > -1) {
        this.form.mediaFiles.splice(index, 1);
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // TODO: 调用保存接口
          this.$emit("success");
          this.cancel();
        }
      });
    },
    cancel() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    resetForm() {
      this.form = {
        playerId: undefined,
        type: undefined,
        content: "",
        mediaFiles: [],
      };
      this.fileList = [];
      this.$refs.form && this.$refs.form.resetFields();
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
.el-upload__tip {
  line-height: 1.2;
}
</style>
